package spring.cloud.tasks.client;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.TimeUnit;

@Slf4j
public class ZooKeepersConnectAndWorkerTasksInitThread extends Thread {

    Worker worker;
    volatile boolean stop = false;

    public ZooKeepersConnectAndWorkerTasksInitThread(Worker worker) {
        this.worker = worker;
    }

    public void stopInitThread() {
        this.stop = true;
    }

    @Override
    public void run() {
        worker.lock.lock();
        try {
            int count = 0;
            while (worker.zooKeeperManager.zooKeeperIsConnected() == false) {
                count = count + 1;
                if (count % 50 == 0) {
                    worker.initThreadErrorMessage = "zooKeeper is connecting ......" + worker.zooKeeperManager.getZooKeeperConnectString() + " spendTime:" + count + "(s)";
                    log.error(worker.initThreadErrorMessage);
                }
                TimeUnit.SECONDS.sleep(1);
                if (this.stop == true) {
                    return;
                }
            }
            worker.initTasksAfterZooKeeperConnected();
        } catch (Throwable e) {
            worker.initThreadErrorMessage = e.getMessage();
            log.error(worker.initThreadErrorMessage, e);
        } finally {
            worker.lock.unlock();
        }

    }

}
